<?php

class Runapi extends  Admin_Controller
{

	function __construct()
   {
      parent::__construct();
      $this->load->helper('form');  
   }

    function index(){
    	$result = $this->db->get('api_resource')->result_array();
    	foreach($result as $val){
    		$data['urlarray'][$val['url']] = $val['remark'];
    	}
    	$this->load->view('runapi/index.php',$data);
    }

	function fly_curl($url, $postFields = null) {
	    $ch = curl_init();
	    curl_setopt($ch, CURLOPT_URL, $url);
	    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.1)');
	    curl_setopt($ch, CURLOPT_HEADER, 0);
	    curl_setopt($ch, CURLOPT_FAILONERROR, 0);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    //curl_setopt($ch,CURLOPT_HTTPHEADER,array("Expect:"));
	    if (is_array($postFields) && 0 < count($postFields))
	    {
	        $postBodyString = "";
	        $postMultipart = false;
	        foreach ($postFields as $k => $v)
	        {
	            if("@" != substr($v, 0, 1))//判断是不是文件上传
	            {
	                $postBodyString .= "$k=" . urlencode($v) . "&";
	            }
	            else//文件上传用multipart/form-data，否则用www-form-urlencoded
	            {
	                $postMultipart = true;
	            }
	        }
	        unset($k, $v);
	        curl_setopt($ch, CURLOPT_POST, 1);
	        if ($postMultipart)
	        {
	            curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
	        }
	        else
	        {
	            //var_dump($postBodyString);
	            curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString,0,-1));
	        }
	    }
	    $reponse = curl_exec($ch);
	    //return curl_getinfo($ch);
	    if (curl_errno($ch))
	    {
	        throw new Exception(curl_error($ch),0);
	    }
	    else
	    {
	        $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	        if (200 !== $httpStatusCode)
	        {
	            throw new Exception($reponse,$httpStatusCode);
	        }
	    }
	    curl_close($ch);
	    return $reponse;
	}

	function microtime_float(){
	    list ($usec, $sec) = explode(" ", microtime());
	    return ((float) $usec + (float) $sec);
	}
	 
 	function submit(){
		$start = $end = 0;
	    $url = $this->http_host($_POST['server']).$_POST['url'];
	    $param = array();
	  
	    if (isset($_POST['param'])) {
	        foreach($_POST['param'] as $k => $item) {
	            if (!empty($_POST['method']) && !empty($item['name'])) {
	                $param[$_POST['method']][$item['name']] = $item['value'];
	            }
	        }
	    }
	      
	    if (isset($param['get']) && !empty($param['get'])) {
	        foreach ($param['get'] as $name => $value) {
	        	if (strstr($url, '?')) {
			       $url = sprintf("%s&%s=%s", $url, $name, $value);;
			    } else {
			       $url = sprintf("%s?%s=%s", $url, $name, $value);
			    }
			            
	        }
	    }
	    $post_data = null;
	    if (isset($param['post']) && !empty($param['post'])) {
	        $post_data = $param['post'];
	    }
	    
	    $start =  $this->microtime_float();
	    $return = $this->fly_curl($url, $post_data);
	    $content = json_decode(urldecode($return), TRUE);
	   
	    if ( ! $content) {
	        $content = $return;
	    }
	    $end =  $this->microtime_float();

	    echo "<pre>";
        echo "请求时间:";
        print_r($end - $start);
         
        echo "<br />请求url:";
        isset($url) && print_r($url);
         
        echo "<br />请求参数:";
        isset($param) && print_r($param);
         
        echo "<hr />结果：";
        if (isset($content['result'])) {
            echo "<br />code:";
            print_r($content['result']['code']);
            echo "message:";
            print_r($content['result']['message']);
            echo "data:";
            print_r($content['result']['data']);
        } else {
            print_r($content);
        }
         
        echo "</pre>";
		// echo json_encode($content);

	}



	function add_view(){
		$this->load->view('runapi/add.php');
	}


	function save(){
		$data['url'] = $_POST['url'];
		$data['method'] = $_POST['method'];
		$data['remark'] = $_POST['remark'];
		$data['doc'] = $_POST['doc'];
		$data['params'] = implode($_POST['params'],'|');
		$this->db->insert("api_resource",$data);
	}

	function load_page(){
		$url = $_GET['url'];
		$res =$this->db->where(array('url'=>$url))->get('api_resource')->result_array();
		echo json_encode($res[0]);
	}


	function http_host($type){
		switch ($type) {
			case 'dev':
				$http_host = 'http://localhost';
				break;
			case 'test':
				$http_host = 'http://119.23.141.210:10030';
				break;
			case 'online':
				$http_host = 'http://119.23.141.210:10030';
				break;
			default:
				$http_host = 'http://119.23.141.210:10030';
				break;
		}
		return $http_host;
	}
}
